//
//  WDViewController.m
//  CommunityApp
//
//  Created by 秦乾龙 on 16/12/6.
//  Copyright © 2016年 秦乾龙. All rights reserved.
//

#import "WDViewController.h"
#import "AFNetworking.h"//主要用于网络请求方法
#import "UIKit+AFNetworking.h"//里面有异步加载图片的方法
#import "AFHTTPSessionManager.h"
#import "UIButton+WebCache.h"
#import "UIImageView+WebCache.h"
#import "NavView.h"
#import "User.h"
#import "ZYButton.h"
#import "WDData.h"
#import "ZYTableViewCell.h"
#import "SetViewController.h"
#import "sellerCenterViewController.h"
#import "MyOrderViewController.h"
#import "MyHomePageViewController.h"
#import "HisHomePageViewController.h"
#import "MyCareViewController.h"
#import "IdentitySureViewController.h"
#import "IdentitySuccessViewController.h"
#import "IdentityFourViewController.h"
#import "IndexViewController.h"
#import "MsgCenterViewController.h"
#import "BaseTabBarControllerConfig.h"
#import "CYLTabBarController.h"
#import "TabBarPublishButton.h"
#import "QBImagePickerController.h"
#import "FansViewController.h"
#import "GCQiniuUploadManager.h"
#import "OrderEvaluationViewController.h"
#import "MycollectionViewController.h"
#import "MyCollectViewController.h"
#define kScreenW [UIScreen mainScreen].bounds.size.width
#define kScreenH [UIScreen mainScreen].bounds.size.height
#define kScale   ([UIScreen mainScreen].bounds.size.width)/750

@interface WDViewController ()<UITableViewDelegate,UITableViewDataSource,QBImagePickerControllerDelegate, UIAlertViewDelegate>
@property(nonatomic,retain)UITableView *mainTableView;
@property(nonatomic,retain)User *user;
@property (strong, nonatomic) UILabel *noticecount;
@property (strong, nonatomic) UIImage *chooseImage;
@property (strong, nonatomic) NSMutableArray *imgurlArray;
@property (strong, nonatomic) NSMutableArray *imgidArray;
@property (strong, nonatomic) NSString *isAuth;
@property (strong, nonatomic) NSString *checkType;

@end

@implementation WDViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _mainTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, kScreenW, kScreenH-64-49) style:UITableViewStyleGrouped];
    _mainTableView.delegate = self;
    _mainTableView.dataSource = self;
    [self.view addSubview:_mainTableView];
    self.view.userInteractionEnabled = YES;
    self.mainTableView.userInteractionEnabled = YES;
}
- (void) setUI
{
    [ViewFactory setNavigationBlack:self];
    self.navigationItem.titleView = [ViewFactory makeNavigationTitle:@"我的"];
    
//    UIButton *buttonNotice = [UIButton buttonWithType:UIButtonTypeCustom];
//    buttonNotice.frame = CGRectMake(0, 0, 20, 20);
//    [buttonNotice setBackgroundImage:[UIImage imageNamed:@"topnotice.png"] forState:UIControlStateNormal];
//    self.noticecount = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, 10, 10)];
//    self.noticecount.font = [FontTool fontWithSize:10];
//    self.noticecount.textAlignment = NSTextAlignmentCenter;
//    self.noticecount.textColor = [UIColor whiteColor];
//    self.noticecount.backgroundColor = [UIColor colorWithHexString:@"0EA1B6"];
//    self.noticecount.layer.masksToBounds = YES;
//    self.noticecount.layer.cornerRadius = 5.f;
//    self.noticecount.text = @"1";
//    self.noticecount.hidden = YES;
//    self.noticecount.userInteractionEnabled = NO;
//    [buttonNotice addSubview:self.noticecount];
//    UIBarButtonItem *btnNoticeItem = [[UIBarButtonItem alloc]initWithCustomView:buttonNotice];
//    [buttonNotice addTarget:self action:@selector(clickNotice:) forControlEvents:UIControlEventTouchUpInside];
//    self.navigationItem.rightBarButtonItem = btnNoticeItem;
    [self addRefreshHeader:_mainTableView];
}

- (void)getMsgCount {
    DYBaseRequest *request = [DYBaseRequest new];
    request.requestUrl = [NSString stringWithFormat:@"%@/sys/index/message/count", APIYIGOU];
    [request dyBgStartWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        NSDictionary *dict = [NSDictionary changeType:request.responseJSONObject];
        NSInteger count = [[dict objectForKey:@"data"] integerValue];
        self.noticecount.text = [NSString stringWithFormat:@"%ld", count];
        if (count == 0) {
            self.noticecount.hidden = YES;
        } else {
            self.noticecount.hidden = NO;
        }
    } error:^(YTKBaseRequest *request) {
        
    } failure:^(YTKBaseRequest *request) {
    }];
}

//下拉刷新
- (void)refresh {
    [super refresh];
    [self request];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self setUI];

    
    [self request];
    [self getMsgCount];
}
- (void)request
{
    NSString *urlStr = [NSString stringWithFormat:@"%@/userCenter/userCenterIndex",APIYIGOU]
    ;
    DYBaseRequest *request = [DYBaseRequest new];
    request.requestUrl = urlStr;
    [request dyBgStartWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        NSDictionary *allDic = [NSDictionary changeType:request.responseJSONObject];
        _user = [[User alloc]initWithDic:allDic[@"data"]];
        [_mainTableView reloadData];
        [_mainTableView.header endRefreshing];
        NSLog(@"1111111%@",allDic);
    } error:^(YTKBaseRequest *request) {
        [_mainTableView.header endRefreshing];
    } failure:^(YTKBaseRequest *request) {
        [_mainTableView.header endRefreshing];
        [ViewFactory showErrorStrMsg:NETWORK_ERR];
    }];
    NSString *urlStr2 =[NSString stringWithFormat:@"%@/userCenter/sellercheck",APIYIGOU];
    
    DYBaseRequest *request2 = [DYBaseRequest new];
    request2.requestUrl = urlStr2;
    [request2 dyBgStartWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        NSDictionary *allDic = [NSDictionary changeType:request.responseJSONObject];
        NSLog(@"2222222%@",allDic);
        _isAuth = [NSString stringWithFormat:@"%@",allDic[@"data"][@"auth"]] ;

        if ([_isAuth isEqualToString:@""]) {
            _checkType = allDic[@"data"][@"hyWaitShop"][@"checktype"];
            [WDData sharedWDData].reallyName = allDic[@"data"][@"hyWaitShop"][@"user_name"];
            [WDData sharedWDData].idcar = allDic[@"data"][@"hyWaitShop"][@"idcar"];
            [WDData sharedWDData].checkType = allDic[@"data"][@"hyWaitShop"][@"checktype"];
        }
        
        
    } error:^(YTKBaseRequest *request) {
        
    } failure:^(YTKBaseRequest *request) {
        [ViewFactory showErrorStrMsg:NETWORK_ERR];
    }];

}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 4;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section==0)
    {
        return 1;
    }
    else if (section==1)
    {
        return 4;
    }
    else if (section==2)
    {
        return 1;
    }
    return 1;
}
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString * identifier = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell)
    {
        cell =[[NSBundle mainBundle ]loadNibNamed:@"ZYTableViewCell" owner:nil options:nil][0];
    }
    //设置cell点击背景色不变
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    if (indexPath.section==0)
    {
        CGFloat publicSpace = 30*kScale;
        CGFloat headerImageH = 160*kScale;
        ZYButton *headerImage = [ZYButton buttonWithType:UIButtonTypeCustom];
        [headerImage sd_setBackgroundImageWithURL:[NSURL URLWithString:_user.headerImageUrl] forState:UIControlStateNormal placeholderImage:[UIImage imageNamed:@""] options:SDWebImageAllowInvalidSSLCertificates];
        if (self.chooseImage) {
            [headerImage setBackgroundImage:self.chooseImage forState:UIControlStateNormal] ;
            
        }
        NSLog(@"222%@",_user.headerImageUrl);
        headerImage.frame = CGRectMake(kScreenW/2-headerImageH/2, publicSpace, headerImageH, headerImageH);
        headerImage.layer.masksToBounds = YES; //没这句话它圆不起来
        headerImage.layer.cornerRadius = 80*kScale;
        [headerImage addTarget:self action:@selector(headerChageClick:) forControlEvents:UIControlEventTouchUpInside];
        
        [cell addSubview:headerImage];
        CGFloat nameLableH = 42*kScale; 
        UILabel *namelable = [[UILabel alloc]initWithFrame:CGRectMake(0, headerImageH+2*publicSpace, kScreenW, nameLableH)];
        namelable.text= [StringHelper replaceUnicode:_user.name];
        namelable.textAlignment = NSTextAlignmentCenter;
        [cell addSubview:namelable];
        
        UIView *lineView = [[UIView alloc]initWithFrame:CGRectMake(kScreenW/2-15*kScale, headerImageH+nameLableH+3*publicSpace, 30*kScale, 2)];
        lineView.backgroundColor = [UIColor blackColor];
        [cell addSubview:lineView];
        
        UILabel *persionSignLable = [[UILabel alloc]init];
        persionSignLable.frame = CGRectMake(0, 0, 354*kScale, nameLableH);
        persionSignLable.font = [UIFont systemFontOfSize:13];
        persionSignLable.center =CGPointMake(kScreenW/2, 4*publicSpace+nameLableH+headerImageH+nameLableH/2);
        persionSignLable.text = _user.personSign;
        persionSignLable.textAlignment = NSTextAlignmentCenter;
        NSLog(@"55555%@",_user.personSign);
        [cell addSubview:persionSignLable];

        UIImageView *blackView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 448*kScale, kScreenW, 164*kScale)];
        blackView.image = [UIImage imageNamed:@"组 36"];
        [cell addSubview:blackView];
        NSArray *signNameArr = [[NSArray alloc]initWithObjects:@"收藏",@"粉丝",@"关注",@"活跃度", nil];
        NSArray *signCountArr = [[NSArray alloc]initWithObjects:_user.collectionCount,_user.personcount,_user.careCount,_user.active, nil];
        for (int i=0; i<4; i++)
        {
            UILabel *signNameLable = [[UILabel alloc]init];
            signNameLable.text = signNameArr[i];
            signNameLable.frame = CGRectMake(kScreenW/4*i, (164*kScale-50)/5*3, kScreenW/4, 30);
            signNameLable.textAlignment=NSTextAlignmentCenter;
            signNameLable.textColor = [UIColor whiteColor];
            [blackView addSubview:signNameLable];
            UILabel *signCountLable = [[UILabel alloc]init];
            if (signCountArr.count!=0) {
                signCountLable.text = [NSString stringWithFormat:@"(%@)",signCountArr[i]];
            }
            
            signCountLable.frame = CGRectMake(kScreenW/4*i, (164*kScale-50)/5*3+30, kScreenW/4, 20);
            signCountLable.font = [UIFont systemFontOfSize:12];
            signCountLable.textAlignment=NSTextAlignmentCenter;
            signCountLable.textColor = [UIColor colorWithRed:178/255.0 green:178/255.0 blue:178/255.0 alpha:1.0f];
            [blackView addSubview:signCountLable];
            if (i>0) {
                UIView *lineView = [[UIView alloc]init];
                lineView.frame = CGRectMake(kScreenW/4*i, (164*kScale-50)/5*3, 2, 50);
                lineView.backgroundColor = [UIColor colorWithRed:78/255.0 green:78/255.0 blue:78/255.0 alpha:1.0f];
                [blackView addSubview:lineView];
            }
        }
    }
    
    else
    {
        NSArray *titleImageNameArr = [[NSArray alloc]initWithObjects:@"我的主页",@"我的关注",@"我收藏的",@"身份认证",@"设置",@"退出登录", nil];
        NSArray *titleArr = [[NSArray alloc]initWithObjects:@"我的主页",@"我的关注",@"我收藏的",@"我的粉丝",@"设置",@"退出登录", nil];
        UIImageView *titleImage = [[UIImageView alloc]init];
        titleImage.frame = CGRectMake(30*kScale, 136/3*kScale, 136/3*kScale, 136/3*kScale);
        UILabel *titleLable = [[UILabel alloc]init];
        titleLable.frame = CGRectMake((30+136/3+26)*kScale, 136/3*kScale, kScreenW, 136/3*kScale);
        if (indexPath.section==1)
        {
            titleImage.image = [UIImage imageNamed:titleImageNameArr[indexPath.row]];
            titleLable.text = titleArr[indexPath.row];
        }
        else if (indexPath.section==2)
        {
            titleImage.image = [UIImage imageNamed:titleImageNameArr[indexPath.row+4]];
            titleLable.text = titleArr[indexPath.row+4];
        }
        
        else if (indexPath.section==3)
        {
            titleImage.image = [UIImage imageNamed:titleImageNameArr[indexPath.row+5]];
            titleLable.text = titleArr[indexPath.row+5];
        }
        [cell addSubview:titleImage];
        [cell addSubview:titleLable];
        //右侧小箭头
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
        return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section==0)
    {
        return  612*kScale;
    }
    return 136*kScale;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section==0)
    {
        return 0.01;
    }
    else if (section==1)
    {
        return 0.01;
    }
    
    return 24*kScale;
}
- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 1)
    {
        NSMutableArray *vcArr = [[NSMutableArray alloc]init];
        
        MyHomePageViewController  *vc1 = [[MyHomePageViewController alloc]init];
        [vcArr addObject:vc1];
        MyCareViewController  *vc2 = [[MyCareViewController alloc]init];
        [vcArr addObject:vc2];
//        sellerCenterViewController  *vc3 = [[sellerCenterViewController alloc]init];
//        [vcArr addObject:vc3];
         MyCollectViewController*vc3 = [[MyCollectViewController alloc]init];
        [vcArr addObject:vc3];
        FansViewController  *vc4 = [[FansViewController alloc]init];
        [vcArr addObject:vc4];
        [self.navigationController pushViewController:vcArr[indexPath.row] animated:YES];
    }
    if (indexPath.section==2)
    {
        SetViewController *set = [[SetViewController alloc]init];
        [self.navigationController pushViewController:set animated:YES];
    }
    if (indexPath.section==3) {
        [self goLogout];
    }
}

- (void)goLogout {
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"确定要退出登录吗？" message:@"" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    [alert show];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 1) { //确定
        [UserData logout];
        CYLTabBarController *base = (CYLTabBarController*)self.tabBarController;
        base.selectedIndex = 0;
    }
}

- (void)clickNotice:(id)sender {
    MsgCenterViewController *vc = [[MsgCenterViewController alloc] initWithNibName:@"MsgCenterViewController" bundle:nil];
    [self.navigationController pushViewController:vc animated:YES];
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.01;
}
//点击头像
-(void)headerChageClick:(ZYButton*)sender
{
    UIAlertController* alertVC = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction* cancleAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    
    UIAlertAction* takePhotoAction = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self openCamera];
    }];
    
    UIAlertAction* choosePictureAction = [UIAlertAction actionWithTitle:@"从手机相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self choosePhoto];
    }];
    
    [alertVC addAction:cancleAction];
    [alertVC addAction:takePhotoAction];
    [alertVC addAction:choosePictureAction];
    
    [self presentViewController:alertVC animated:YES completion:nil];
}

- (void)openCamera {
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
    
    if (![UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]) {
        sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    }
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.delegate = self;
    picker.sourceType = sourceType;
    
    [self presentViewController:picker animated:YES completion:^{
    }];
}

- (void)choosePhoto {
    NSInteger maxCount = 1;
    QBImagePickerController *imagePickerController = [QBImagePickerController new];
    imagePickerController.assetCollectionSubtypes =@[
                                                     @(PHAssetCollectionSubtypeSmartAlbumUserLibrary), //相机胶卷
                                                     @(PHAssetCollectionSubtypeAlbumMyPhotoStream), //我的照片流
                                                     @(PHAssetCollectionSubtypeSmartAlbumPanoramas), //全景图
                                                     @(PHAssetCollectionSubtypeSmartAlbumBursts), //连拍模式拍摄的照片
                                                     @(PHAssetCollectionSubtypeSmartAlbumFavorites)
                                                     ];
    imagePickerController.delegate = self;
    imagePickerController.allowsMultipleSelection = YES;
    imagePickerController.mediaType = QBImagePickerMediaTypeImage;
    imagePickerController.maximumNumberOfSelection = maxCount;
    imagePickerController.showsNumberOfSelectedAssets = YES;
    [self presentViewController:imagePickerController animated:YES completion:nil];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo {
    [picker dismissViewControllerAnimated:YES completion:^{
        self.chooseImage = image;
        [self uploadImages];
    }];
}

- (void)qb_imagePickerController:(QBImagePickerController *)imagePickerController didFinishPickingAssets:(NSArray *)assets {
    NSUInteger count = assets.count;
    __block NSUInteger select = 0;
    PHImageRequestOptions *option = [[PHImageRequestOptions alloc] init];
    option.synchronous = YES;
    for (PHAsset *asset in assets) {
        [[PHCachingImageManager defaultManager]requestImageDataForAsset:asset options:option resultHandler:^(NSData * imageData, NSString * dataUTI, UIImageOrientation orientation, NSDictionary * info) {
            if(imageData) {
                self.chooseImage = [UIImage imageWithData:imageData];
                select++;
            }
            if(select == count) {
                [imagePickerController dismissViewControllerAnimated:YES completion:NULL];
                [self uploadImages];
                return;
            }
        }];
        
    }
}

- (void)qb_imagePickerControllerDidCancel:(QBImagePickerController *)imagePickerController {
    [imagePickerController dismissViewControllerAnimated:NO completion:NULL];
}

- (void)uploadImages {
    
    
    [self.imgurlArray removeAllObjects];
    [self.imgidArray removeAllObjects];
    NSMutableArray *dataarray = [NSMutableArray new];
    [dataarray addObject:UIImageJPEGRepresentation(self.chooseImage, NORMALSIZE)];
    
    [[GCQiniuUploadManager sharedInstance] uploadDatas:dataarray progress:^(float percent) {
        
    } oneTaskCompletion:^(NSError *error, NSString *link, NSInteger index) {
        DYLog(@"upload index:%ld link:%@", index, link);
        if (link) {
            NSString *resurl = [NSString stringWithFormat:@"%@/%@", @"https://7xvu4i.com1.z0.glb.clouddn.com", link];
            [self.imgurlArray addObject:resurl];
            [self.imgidArray addObject:link];
            //修改头像
            NSString *urlStr = [NSString stringWithFormat:@"%@/userCenter/modifyMemberHeadUrl?head_url=%@",APIYIGOU,resurl];
            ;
            DYBaseRequest *request = [DYBaseRequest new];
            request.requestUrl = urlStr;
            [request dyBgStartWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
                NSDictionary *allDic = [NSDictionary changeType:request.responseJSONObject];
                [UserData setUserheadurl:resurl];
                [_mainTableView reloadData];
                NSLog(@"1111111%@",allDic);
            } error:^(YTKBaseRequest *request) {
                
            } failure:^(YTKBaseRequest *request) {
                [ViewFactory showErrorStrMsg:NETWORK_ERR];
            }];
        }
    } allTasksCompletion:^{
        //[self uploadDoc];
    }];
}

//设置状态栏颜色
- (UIStatusBarStyle)preferredStatusBarStyle
{
    return UIStatusBarStyleLightContent;
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
